package define;

import main.ConditionException;

public enum CompareType 
{
	E_BIGGER_CT(">"),
	E_SMALLER_CT("<"),
	E_NO_BIGGER_CT("<="),
	E_NO_SMALLER_CT(">="),
	E_EQURE_CT("=="),
	E_UNEQURE_CT("!="),
	E_HAS_CT("has"),
	E_UNHAS_CT("!has"),
	E_NO_CT("!"),
	E_AND_CT("a"),
	E_OR_CT("o"),
	E_CHILD_START_CT("("),
	E_CHILD_END_CT(")"),
	;
	
	private String m_exp;
	
	private CompareType(String exp)
	{
		m_exp = exp;
	}
	
	public String getExp()
	{
		return m_exp;
	}
	
	public static CompareType isCompare(String exp)
	{
		exp = exp.toLowerCase();
		for(CompareType ct: CompareType.values())
		{
			if(ct.getExp().compareTo(exp) == 0)
			{
				return ct;
			}
		}
		return null;
	}
	
	public static boolean isLogic(String exp)
	{
		exp = exp.toLowerCase();
		for(int i = E_AND_CT.ordinal(); i <= E_OR_CT.ordinal(); ++i)
		{
			if(exp.compareTo(CompareType.values()[i].getExp()) == 0)
			{
				return true;
			}
		}
		return false;
	}
	
	public boolean getLogicValue(boolean left, boolean right, int position) throws ConditionException
	{
		switch(this)
		{
		case E_AND_CT:
			return left && right;
		case E_OR_CT:
			return left || right;
		default:
			throw new ConditionException(ErrorDefine.E_CONDITION_TYPE_ERROR, position);
		}
	}
	
	public static CompareType getCompare(String exp)
	{
		exp = exp.toLowerCase();
		for(CompareType ct: CompareType.values())
		{
			if(ct.getExp().compareTo(exp) == 0)
			{
				return ct;
			}
		}
		return null;
	}
	
	public boolean getCompareValue(String left, String right, int position) throws ConditionException
	{
		Double i1 = null;
		Double i2 = null;
		if(this.ordinal() <= E_NO_SMALLER_CT.ordinal())
		{
			i1 = Common.isNumber(left);
			i2 = Common.isNumber(right);
			if(i1 == null || i2 == null)
			{
				throw new ConditionException(ErrorDefine.E_COMPARE_MUST_NUMBER_ERROR, position);
			}
		}
		switch(this) 
		{
		case E_BIGGER_CT:
			return i1 > i2;
		case E_SMALLER_CT:
			return i1 < i2;
		case E_NO_BIGGER_CT:
			return i1 <= i2;
		case E_NO_SMALLER_CT:
			return i1 >= i2;
		case E_EQURE_CT:
			return left.compareTo(right) == 0;
		case E_UNEQURE_CT:
			return left.compareTo(right) != 0;
		default:
			throw new ConditionException(ErrorDefine.E_CONDITION_TYPE_ERROR, position);
		}
	}
}
